import axios from 'axios'

// 基础配置：优先使用环境变量 VITE_API_BASE_URL
const baseURL = import.meta.env?.VITE_API_BASE_URL || '/'

const http = axios.create({
  baseURL,
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器：自动注入本地存储的 token
http.interceptors.request.use(
  (config) => {
    const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null
    if (token) {
      config.headers = config.headers || {}
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截器：统一返回 data，规范化错误对象
http.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response) {
      const { status, data } = error.response
      // 可根据业务需要处理 401，例如跳转登录或清理本地状态
      if (status === 401) {
        // localStorage.removeItem('token')
        // 可在此触发登出流程或路由跳转
      }
      return Promise.reject({
        status,
        data,
        message: data?.message || error.message || '请求失败'
      })
    }

    if (error.request) {
      // 请求已发出但未收到响应（网络问题或服务器无响应）
      return Promise.reject({
        status: 0,
        message: '网络异常或服务器无响应',
        detail: error.message
      })
    }

    // 其他错误（配置错误等）
    return Promise.reject({ status: 0, message: error.message || '未知错误' })
  }
)

// 常用方法封装
export const get = (url, params = {}, config = {}) => http.get(url, { params, ...config })
export const post = (url, data = {}, config = {}) => http.post(url, data, { ...config })
export const put = (url, data = {}, config = {}) => http.put(url, data, { ...config })
export const del = (url, params = {}, config = {}) => http.delete(url, { params, ...config })

// 文件上传示例（multipart/form-data）
export const upload = (url, formData, config = {}) => {
  return http.post(url, formData, {
    headers: { 'Content-Type': 'multipart/form-data', ...(config.headers || {}) },
    ...config
  })
}

export default http